﻿using CampWeek5__Book_Project_.Adapters.Interfaces;
using CampWeek5__Book_Project_.Data;
using CampWeek5__Book_Project_.Data.Model;
using CampWeek5__Book_Project_.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace CampWeek5__Book_Project_.Adapters.Adapters
{
    public class BookAdapter : IBookAdapter
    {
        public IndexVM SearchBooks(string search)
        {
            IndexVM model = new IndexVM();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                if (search == "TitleSearch")
                {
                    model.Books = db.Books.Where(x => x.Title.ToLower().Contains(search.ToLower())).Select(x => new IndexBookVM()
                    {
                        ISBN = x.ISBN,
                        AuthorId = x.AuthorId,
                        Title = x.Title,
                    }).ToList();
                }
                if (search == "isbnSearch")
                {

                    model.Books = db.Books.Where(x => x.ISBN.Equals(search)).Select(x => new IndexBookVM()
                        {
                            ISBN = x.ISBN,
                            AuthorId = x.AuthorId,
                            Title = x.Title,
                        }).ToList();
                }
            };
            return model;
        }

        public IndexVM GetIndex()
        {
            IndexVM model = new IndexVM();
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model.Books = db.Books.Where(x => x.DateDeleted == null).OrderByDescending(x => x.TimesViewed).Take(10).Select(x => new IndexBookVM()
                {
                    AuthorId = x.AuthorId,
                    BookImg = x.BookImg,
                    AuthorName = x.Author.AuthorName,
                    Title = x.Title,
                    ISBN = x.ISBN,
                    BookRating = (x.BookRatings.Count > 0) ? x.BookRatings.Select(r => r.BookRating).Average() : 0
                }).ToList();

                model.FeaturedBook = Featured.FeaturedBook;

                model.Authors = db.Authors.Where(x => x.DateDeleted == null).OrderByDescending(x => x.TimesViewed).Take(10).Select(x => new IndexAuthorVM()
                {
                    AuthorImg = x.AuthorImg,
                    AuthorId = x.Id,
                    AuthorName = x.AuthorName
                }).ToList();
            }
            return model;
        }

        public void CreateRating(Rating rating)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                db.Ratings.Add(rating);
                db.SaveChanges();
            }
        }

        public Book FindBookByISBN(int isbn)
        {
            Book model;
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model = db.Books.Include("Author").Include("BookRatings").FirstOrDefault(x => x.ISBN == isbn);
            }
            return model;

        }

        public void DeleteRating(int id)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Rating model = db.Ratings.FirstOrDefault(x => x.Id == id);
                model.DateDeleted = DateTime.Now;
                db.SaveChanges();
            }

        }


        public BookVM CreateBook(BookVM book)
        {
            List<string> tags = book.Tags[0].Split(',').ToList();
            ApplicationDbContext db = new ApplicationDbContext();

            if (!db.Books.Any(x => x.ISBN == book.ISBN))
            {

                Book model = new Book()
                {
                    AuthorId = book.AuthorId,
                    BookImg = book.BookImg,
                    DateDeleted = null,
                    ISBN = book.ISBN,
                    PubDate = book.PubDate,
                    Summary = book.Summary,
                    TimesViewed = 0,
                    Title = book.Title
                };
                using (db = new ApplicationDbContext())
                {
                    db.Books.Add(model);
                    db.SaveChanges();

                    foreach (var t in tags)
                    {
                        string trimmedT = t.Trim();
                        if (db.Tags.Any(x => x.Description.ToLower() == trimmedT.ToLower()))
                        {
                            Tag tag = db.Tags.FirstOrDefault(x => x.Description.ToLower() == trimmedT.ToLower());
                            db.Book_Tags.Add(new Book_Tags() { TagId = tag.Id, BookId = model.Id });
                            db.SaveChanges();
                        }
                        else
                        {
                            Tag tag = new Tag() { Description = trimmedT };
                            db.Tags.Add(tag);
                            db.Book_Tags.Add(new Book_Tags() { BookId = model.Id, TagId = tag.Id });
                            db.SaveChanges();
                        }
                    }
                }
            }
            return (book);

        }

        public void DeleteBook(int Id)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                Book model = db.Books.FirstOrDefault(x => x.Id == Id);
                model.DateDeleted = DateTime.Now;
                db.SaveChanges();
            }
        }

        public BookVM AdminEditGetBook(int Id, BookVM model)
        {

            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                model = db.Books.Where(x => x.Id == Id).Select(x => new BookVM()
                {
                    ISBN = x.ISBN,
                    PubDate = x.PubDate,
                    Summary = x.Summary,
                    Tags = x.Book_Tags.Select(t => t.Tag.Description).ToList(),
                    TimesViewed = x.TimesViewed,
                    Title = x.Title,
                    AuthorId = x.AuthorId,
                    DateDeleted = null,
                    AuthorName = x.Author.AuthorName,
                    BookImg = x.BookImg,
                    Id = x.Id,
                }

                    ).FirstOrDefault();
            }
            return (model);
        }

        public BookVM AdminEditBook(BookVM book)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                List<string> tags = book.Tags[0].Split(',').ToList();
                Book tempBook = db.Books.FirstOrDefault(x => x.Id == book.Id);
                tempBook.ISBN = book.ISBN;
                tempBook.Title = book.Title;
                tempBook.AuthorId = book.AuthorId;
                tempBook.PubDate = book.PubDate;
                tempBook.Summary = book.Summary;
                tempBook.BookImg = book.BookImg;
                db.SaveChanges();

                List<string> dbtags = tempBook.Book_Tags.Select(x => x.Tag.Description).ToList();
                for (var i = 0; i < tags.Count; i++)
                {
                    tags[i] = tags[i].Trim();
                }

                //tempBook.Book_Tags.RemoveAll(t => !tags.Contains(t.Tag.Description));
                //db.SaveChanges();
                var newTags = tags.Except(dbtags);
                foreach (var t in newTags)
                {
                    Tag tag;
                    if (db.Tags.Any(x => x.Description == t))
                    {
                        tag = db.Tags.FirstOrDefault(x => x.Description == t);
                    }
                    else
                    {
                        tag = new Tag() { Description = t };
                        db.Tags.Add(tag);
                    }
                    Book_Tags item = new Book_Tags() { BookId = tempBook.Id, TagId = tag.Id };
                    db.Book_Tags.Add(item);
                }
                db.SaveChanges();
            }
            return (book);
        }






    }
}